package com.chenailin.www.controller;

import com.chenailin.www.pojo.Administrator;
import com.chenailin.www.pojo.Student;
import com.chenailin.www.pojo.User;
import com.chenailin.www.service.PublicService;

import java.util.Scanner;

import static com.chenailin.www.util.MenuUtil.showAdminMenu;
import static com.chenailin.www.util.MenuUtil.showStudentMenu;

public class PublicController {
    private final PublicService publicService = new PublicService();
    private final Scanner sc = new Scanner(System.in);
    public Administrator loginAdministrator;
    public Student loginStudent;

    // 登录功能
    public void login() {
        System.out.println("===== 用户登录 =====");
        try {
            if (!publicService.hasAccounts()) {
                System.out.print("系统中无账户，请先注册");
                return;
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        int userType;
        while (true) {
            System.out.println("请您选择你的身份：\n1.管理员\n2.学生");
            userType = sc.nextInt();
            if (userType == 1 || userType == 2) {
                break;
            } else {
                System.out.println("无效选项，请重新输入");
            }
        }
        System.out.println("请输入账号:");
        int id = sc.nextInt();
        sc.nextLine();
        User user = publicService.login(id, userType);
        // 初始化登录用户对象
        if (userType == 1) {
            loginAdministrator = (Administrator) user;
        } else {
            loginStudent = (Student) user;
        }
        try {
            boolean test =  handlePasswordValidation(user.getPassword());
            if(test) {
                System.out.println("\n登录成功！");
                redirectToMenu(userType);
            }
        } catch (Exception e) {
            System.err.println("数据库连接失败: " + e.getMessage());
        }
    }

    // 注册功能
    public void register() {
        System.out.println("===== 用户注册 =====");
        int userType;
        while (true) {
            System.out.println("请您选择你的身份：\n1.管理员\n2.学生");
            userType = sc.nextInt();
            if (userType == 1 || userType == 2) {
                break;
            } else {
                System.out.println("无效选项，请重新输入");
            }
        }
        Student stu = null;
        Administrator admin = null;
        int id;
        if (userType == 1) {
            System.out.println("请输入工号:");
            id = sc.nextInt();
            sc.nextLine();
            String password = confirmPassword();
            admin = new Administrator(id, password);
        } else {
            System.out.println("请输入学号:");
            id = sc.nextInt();
            sc.nextLine();
            System.out.println("请输入姓名:");
            String name = sc.nextLine();
            System.out.println("请输入电话号码:");
            String tel = sc.nextLine();
            System.out.println("请输入年龄:");
            int age = sc.nextInt();
            sc.nextLine();
            String password = confirmPassword();
            stu = new Student(id, name, age, tel, password);
        }
        try {
            boolean success = (userType == 1) ? publicService.register(admin, userType) : publicService.register(stu, userType);
            if (!success) {
                System.out.println("注册失败：该账号已存在");
            } else {
                System.out.println("\n注册成功！");
            }
        } catch (Exception e) {
            System.err.println("数据库连接失败: " + e.getMessage());
        }
    }

    // 确认密码
    private String confirmPassword() {
        while (true) {
            System.out.println("请输入密码:");
            String password = sc.nextLine();
            System.out.println("请确认密码:");
            String confirm = sc.nextLine();

            if (password.equals(confirm)) {
                return password;
            }
            System.out.println("两次输入不一致，请重新输入");
        }
    }

    // 密码错误三次退出系统
    private boolean handlePasswordValidation(String dbPassword) {
        final int MAX_ATTEMPTS = 3;
        int attempts = 0;

        while (attempts < MAX_ATTEMPTS) {
            System.out.print("请输入密码（剩余次数：" + (MAX_ATTEMPTS - attempts) + "）: ");
            String input = sc.nextLine();

            if (publicService.arePasswordsEqual(input, dbPassword)) {
                System.out.println("密码正确，登录成功！");
                return true;
            }
            System.out.println("密码错误！");
            attempts++;
        }
        System.out.println("错误次数过多，系统退出！");
        System.exit(0);
        return false; // 实际不会执行到此处
    }

    // 处理重试逻辑
    private boolean handleRetry() {
        System.out.println("1.重新输入\n" + "0.退出");
        int retry = sc.nextInt();
        sc.nextLine(); // 清除换行符
        return retry != 1;
    }

    // 菜单跳转
    private void redirectToMenu(int userType) {
        if (userType == 1) {
            showAdminMenu(loginAdministrator);
        } else {
            showStudentMenu(loginStudent);
        }
    }
}
